import {computed, designPage, getComponentCls, iMouseEvent, reactive} from "plain-design-composition";
import {DemoRow} from "../../Demo/DemoRow";
import {$message, Adc, AdcGroup, AdcInput, AntdTable, Button} from "../../../../packages";
import DATA from '../../../data/data-1.json';
import {deepcopy} from "plain-utils/object/deepcopy";
import {iAdcColumn, iAdcPropsType} from "../../../../packages/components/AntdTable/adc/adc.utils";
import {iAdtNode} from "../../../../packages/components/AntdTable/utils/antd-table.utils";
import {AdcSwitch} from "../../../../packages/components/AdcSwitch";
import {PlainObject} from "plain-utils/utils/event";
import {ColumnsType} from "antd/es/table";
import {Table, TableProps} from "antd";

export const demo1 = designPage(() => {

  const state = reactive({
    dataSource: deepcopy(DATA),
    editNodes: [] as iAdtNode[]
  });

  const handler = {
    onClickCell: (data: any, e: iMouseEvent, adc: iAdcColumn) => {
      console.log('click cell', data[adc.props.dataIndex as string]);
    },
    onRowDoubleClick: ({ node }: { node: iAdtNode }) => {
      node.enableEdit();
      state.editNodes.findIndex(i => i.state.index === node.state.index) === -1 && state.editNodes.push(node);
    },
    save: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancel: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  };

  const isDisabledOperation = computed(() => state.editNodes.length === 0);

  const nameColumnAttrs: iAdcPropsType = {
    width: 120,
    filterMultiple: true,
    filters: Array.from(new Set(state.dataSource.map(i => i.name).filter(Boolean))).map(i => ({
      text: i,
      value: i,
    })),
    onFilter: (value: any, record: PlainObject) => record.name.indexOf(value) === 0,
    sorter: true,
    /*第一次点击的时候升序排序*/
    defaultSortOrder: 'ascend',
  };

  const addressColumnAttrs: iAdcPropsType = {
    width: 180,
    filterMode: 'tree',
    filterMultiple: true,
    filters: [
      {
        text: '云南省', value: '云南省',
        children: [
          { text: '曲靖市', value: '曲靖市' },
          { text: '德宏傣族', value: '德宏傣族' },
          { text: '怒江', value: '怒江' },
        ]
      },
      {
        text: '山东省', value: '山东省',
        children: [
          { text: '烟台', value: '烟台' },
          { text: '淄博市', value: '淄博市' },
        ]
      },
      {
        text: '广东省', value: '广东省',
        children: [
          { text: '河源市', value: '河源市' },
          { text: '广州市', value: '广州市' },
        ]
      },
    ]
  };

  return () => (
    <DemoRow title="基本用法">
      <div className={getComponentCls('antd-table-outer-operation')}>
        <Button label="取消" disabled={isDisabledOperation.value} onClick={handler.cancel}/>
        <Button label="保存" type="primary" disabled={isDisabledOperation.value} onClick={handler.save}/>
      </div>
      <AntdTable
        dataSource={state.dataSource}
        onRowDoubleClick={handler.onRowDoubleClick}
        showRows={10}
      >
        <Adc title={'普通文本列'} dataIndex={'id'} onCellClick={handler.onClickCell}/>
        <Adc title={'设置宽度'} dataIndex={'id'}/>
        <AdcInput title={'大小'} dataIndex={'size'} onCellClick={handler.onClickCell} sorter/>
        <AdcGroup title="联系方式">
          <AdcInput title={'地址'} dataIndex={'addr'} {...addressColumnAttrs}/>
          <AdcInput title={'链接'} dataIndex={'url'}/>
        </AdcGroup>
        <AdcGroup title={'地址'}>
          <AdcInput dataIndex="date" title="日期"/>
          <AdcInput dataIndex="name" title="名称" {...nameColumnAttrs}/>
          <AdcInput dataIndex="color" title="颜色"/>
          <AdcSwitch dataIndex="flag" title="开关"/>
        </AdcGroup>
      </AntdTable>
    </DemoRow>
  );
});


export const demo2 = designPage(() => {

  const state = reactive({
    dataSource: deepcopy(DATA),
    editNodes: [] as iAdtNode[]
  });

  const handler = {
    onClickCell: (data: any, e: iMouseEvent, adc: iAdcColumn) => {
      console.log('click cell', data[adc.props.dataIndex as string]);
    },
    onRowDoubleClick: ({ node }: { node: iAdtNode }) => {
      node.enableEdit();
      state.editNodes.findIndex(i => i.state.index === node.state.index) === -1 && state.editNodes.push(node);
    },
    save: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancel: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  };

  const isDisabledOperation = computed(() => state.editNodes.length === 0);

  const nameColumnAttrs: iAdcPropsType = {
    width: 120,
    filterMultiple: true,
    filters: Array.from(new Set(state.dataSource.map(i => i.name).filter(Boolean))).map(i => ({
      text: i,
      value: i,
    })),
    onFilter: (value: any, record: PlainObject) => record.name.indexOf(value) === 0,
    sorter: true,
    /*第一次点击的时候升序排序*/
    defaultSortOrder: 'ascend',
  };

  const addressColumnAttrs: iAdcPropsType = {
    width: 180,
    filterMode: 'tree',
    filterMultiple: true,
    filters: [
      {
        text: '云南省', value: '云南省',
        children: [
          { text: '曲靖市', value: '曲靖市' },
          { text: '德宏傣族', value: '德宏傣族' },
          { text: '怒江', value: '怒江' },
        ]
      },
      {
        text: '山东省', value: '山东省',
        children: [
          { text: '烟台', value: '烟台' },
          { text: '淄博市', value: '淄博市' },
        ]
      },
      {
        text: '广东省', value: '广东省',
        children: [
          { text: '河源市', value: '河源市' },
          { text: '广州市', value: '广州市' },
        ]
      },
    ]
  };

  return () => (
    <DemoRow title="初始的排序状态">
      <div className={getComponentCls('antd-table-outer-operation')}>
        <Button label="取消" disabled={isDisabledOperation.value} onClick={handler.cancel}/>
        <Button label="保存" type="primary" disabled={isDisabledOperation.value} onClick={handler.save}/>
      </div>
      <AntdTable
        dataSource={state.dataSource}
        onRowDoubleClick={handler.onRowDoubleClick}
        showRows={10}
      >
        <Adc title={'普通文本列'} dataIndex={'id'} onCellClick={handler.onClickCell}/>
        <Adc title={'设置宽度'} dataIndex={'id'}/>
        <AdcInput title={'大小'} dataIndex={'size'} onCellClick={handler.onClickCell} sorter sortOrder="descend"/>
        <AdcGroup title="联系方式">
          <AdcInput title={'地址'} dataIndex={'addr'} {...addressColumnAttrs}/>
          <AdcInput title={'链接'} dataIndex={'url'}/>
        </AdcGroup>
        <AdcGroup title={'地址'}>
          <AdcInput dataIndex="date" title="日期"/>
          <AdcInput dataIndex="name" title="名称" {...nameColumnAttrs}/>
          <AdcInput dataIndex="color" title="颜色"/>
          <AdcSwitch dataIndex="flag" title="开关"/>
        </AdcGroup>
      </AntdTable>
    </DemoRow>
  );
});

export const demo3 = designPage(() => {

  const state = reactive({
    dataSource: deepcopy(DATA),
    editNodes: [] as iAdtNode[]
  });

  const handler = {
    onClickCell: (data: any, e: iMouseEvent, adc: iAdcColumn) => {
      console.log('click cell', data[adc.props.dataIndex as string]);
    },
    onRowDoubleClick: ({ node }: { node: iAdtNode }) => {
      node.enableEdit();
      state.editNodes.findIndex(i => i.state.index === node.state.index) === -1 && state.editNodes.push(node);
    },
    save: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(tableNode => tableNode.saveEdit(tableNode.state.editRow));
      state.editNodes.forEach(tableNode => tableNode.closeEdit());
      state.editNodes = [];
    },
    cancel: () => {
      state.editNodes.forEach(tableNode => {
        tableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  };

  const isDisabledOperation = computed(() => state.editNodes.length === 0);

  const nameColumnAttrs: iAdcPropsType = {
    width: 120,
    filterMultiple: true,
    filters: Array.from(new Set(state.dataSource.map(i => i.name).filter(Boolean))).map(i => ({
      text: i,
      value: i,
    })),
    onFilter: (value: any, record: PlainObject) => record.name.indexOf(value) === 0,
    sorter: {
      multiple: 1,
    },
    /*第一次点击的时候升序排序*/
    defaultSortOrder: 'ascend',
  };

  const addressColumnAttrs: iAdcPropsType = {
    width: 180,
    filterMode: 'tree',
    filterMultiple: true,
    filters: [
      {
        text: '云南省', value: '云南省',
        children: [
          { text: '曲靖市', value: '曲靖市' },
          { text: '德宏傣族', value: '德宏傣族' },
          { text: '怒江', value: '怒江' },
        ]
      },
      {
        text: '山东省', value: '山东省',
        children: [
          { text: '烟台', value: '烟台' },
          { text: '淄博市', value: '淄博市' },
        ]
      },
      {
        text: '广东省', value: '广东省',
        children: [
          { text: '河源市', value: '河源市' },
          { text: '广州市', value: '广州市' },
        ]
      },
    ],
  };

  const sizeColumnAttrs: iAdcPropsType = {
    width: 100,
    sorter: {
      multiple: 3,
    },
    sortOrder: 'descend'
  };

  return () => (
    <DemoRow title="多级排序">
      <div className={getComponentCls('antd-table-outer-operation')}>
        <Button label="取消" disabled={isDisabledOperation.value} onClick={handler.cancel}/>
        <Button label="保存" type="primary" disabled={isDisabledOperation.value} onClick={handler.save}/>
      </div>
      <AntdTable
        dataSource={state.dataSource}
        onRowDoubleClick={handler.onRowDoubleClick}
        showRows={10}
      >
        <Adc title={'普通文本列'} dataIndex={'id'} onCellClick={handler.onClickCell}/>
        <Adc title={'设置宽度'} dataIndex={'id'}/>
        <AdcInput title={'大小'} dataIndex={'size'} onCellClick={handler.onClickCell} {...sizeColumnAttrs}/>
        <AdcGroup title="联系方式">
          <AdcInput title={'地址'} dataIndex={'addr'} {...addressColumnAttrs}/>
          <AdcInput title={'链接'} dataIndex={'url'}/>
        </AdcGroup>
        <AdcGroup title={'地址'}>
          <AdcInput dataIndex="date" title="日期"/>
          <AdcInput dataIndex="name" title="名称" {...nameColumnAttrs}/>
          <AdcInput dataIndex="color" title="颜色"/>
          <AdcSwitch dataIndex="flag" title="开关"/>
        </AdcGroup>
      </AntdTable>
    </DemoRow>
  );
});


interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

export const demoOrigin = designPage(() => {

  const columns: ColumnsType<DataType> = [
    {
      title: 'Name',
      dataIndex: 'name',
      filters: [
        {
          text: 'Joe',
          value: 'Joe',
        },
        {
          text: 'Category 1',
          value: 'Category 1',
          children: [
            {
              text: 'Yellow',
              value: 'Yellow',
            },
            {
              text: 'Pink',
              value: 'Pink',
            },
          ],
        },
        {
          text: 'Category 2',
          value: 'Category 2',
          children: [
            {
              text: 'Green',
              value: 'Green',
            },
            {
              text: 'Black',
              value: 'Black',
            },
          ],
        },
      ],
      filterMode: 'tree',
      filterSearch: true,
      filteredValue: ['Joe'],
      onFilter: (value: any, record) => record.name.includes(value),
      sorter: (a, b) => a.age - b.age,
      width: '30%',
    },
    {
      title: 'Age',
      dataIndex: 'age',
      filteredValue: [],
      sorter: (a, b) => a.age - b.age,
    },
    {
      title: 'Address',
      dataIndex: 'address',
      filteredValue: [],
      // filteredValue: ['London'],
      filters: [
        {
          text: 'London',
          value: 'London',
        },
        {
          text: 'New York',
          value: 'New York',
        },
      ],
      onFilter: (value: any, record) => record.address.startsWith(value),
      filterSearch: true,
      width: '40%',
    },
  ];

  const data: DataType[] = [
    {
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New York No. 1 Lake Park',
    },
    {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park',
    },
    {
      key: '3',
      name: 'Joe Black',
      age: 32,
      address: 'Sydney No. 1 Lake Park',
    },
    {
      key: '4',
      name: 'Jim Red',
      age: 32,
      address: 'London No. 2 Lake Park',
    },
  ];

  const state = reactive({
    columns,
    data,
  });

  const onChange: TableProps<DataType>['onChange'] = (pagination, filters, sorter, extra) => {
    console.log('params', { pagination, filters, sorter, extra });

    state.columns.forEach(column => {
      if ('dataIndex' in column && typeof column.dataIndex === 'string') {
        column.filteredValue = filters[column.dataIndex];
      }
    });
    state.columns = [...state.columns];
  };

  return () => (
    <DemoRow title="原始用法">
      <Table columns={columns} dataSource={data} onChange={onChange}/>
    </DemoRow>
  );
});
